package com.asiainfo.ncrm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;




































import com.asiainfo.ncrm.base.MyWebChromeClient;
import com.asiainfo.ncrm.common.Constant;
import com.asiainfo.ncrm.fragment.FragmentPage1;
import com.asiainfo.ncrm.fragment.FragmentPage2;
import com.asiainfo.ncrm.fragment.FragmentPage3;
import com.asiainfo.ncrm.fragment.FragmentPage4;
import com.asiainfo.ncrm.fragment.fragmentPageBase;
import com.asiainfo.ncrm.loading.LoadingView;
import com.asiainfo.ncrm.loading.ShapeLoadingDialog;
import com.asiainfo.ncrm.loading.ShapeLoadingView;
import com.asiainfo.ncrm.nfc.IdCard_Bean;
import com.asiainfo.ncrm.nfc.NFCActivity;
import com.asiainfo.ncrm.update.UpdateManager;
import com.asiainfo.ncrm.util.CustomProgressDialog;
import com.asiainfo.ncrm.util.HttpConstant;
import com.asiainfo.ncrm.util.X;
import com.asiainfo.ncrm.xtnfc.XTNFCActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

@SuppressLint("NewApi")
public class HomeActivity extends FragmentActivity implements
android.view.View.OnClickListener{
	private Handler mHandler = new Handler();
	private Handler printHandler = new Handler();
	private ProgressDialog progressDialog;
	private ProgressDialog updateProgressDialog;
	private String resultStr="请重新调整拍照角度以及光线";
	WebView webview;
	private WindowManager wm = null;
	private JSONObject resultObj;
	private String param;
	private UpdateManager updateMan;
	private boolean isOut = false;
	private boolean isIn = false;
	private boolean ssoLogin = false;
	private String userno = "";
	private String password = "";
	private String staffNumber = "";
	private String olNbr = "";
	private String sign = "";
	private String sysCode = "";
	private String data = "";
	private TelephonyManager tm = null;
	private BluetoothAdapter adapter = null;
	private ValueCallback<Uri> mUploadMessage; // 上传文件时用
	private Context mContext=null;
	
	private CustomProgressDialog customDialog;
	
	    private Dialog mDialog;
	    private LoadingView mLoadingView;
	    private View mDialogContentView;
	    
	    private List<View> mViews = new ArrayList<View>();// 用来存放Tab01-04
		// 四个Tab，每个Tab包含一个按钮
		private LinearLayout mTabWeiXin;
		private LinearLayout mTabAddress;
		private LinearLayout mTabFrd;
		private LinearLayout mTabSetting;
		// 四个按钮
		private ImageButton mWeiXinImg;
		private ImageButton mAddressImg;
		private ImageButton mFrdImg;
		private ImageButton mSettingImg;
		
		private FragmentManager fm = this.getSupportFragmentManager();
		private FragmentTransaction ft;
		private fragmentPageBase fragmentPage1;
		private fragmentPageBase fragmentPage2;
		private fragmentPageBase fragmentPage3;
		private fragmentPageBase fragmentPage4;


		String cookies = "";
		SharedPreferences sp;
		
		private String func;
		
		private String paramString;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mContext=this;
		// 清理webview cookies缓存
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		webview= (WebView) this.findViewById(R.id.mainWebView);
//		
//		mViewPager = (ViewPager) findViewById(R.id.id_viewpage);
		// 初始化四个LinearLayout
//		mTabWeiXin = (LinearLayout) findViewById(R.id.id_tab_weixin);
//		mTabAddress = (LinearLayout) findViewById(R.id.id_tab_address);
//		mTabFrd = (LinearLayout) findViewById(R.id.id_tab_frd);
//		mTabSetting = (LinearLayout) findViewById(R.id.id_tab_settings);
//		// 初始化四个按钮
//		mWeiXinImg = (ImageButton) findViewById(R.id.id_tab_weixin_img);
//		mAddressImg = (ImageButton) findViewById(R.id.id_tab_address_img);
//		mFrdImg = (ImageButton) findViewById(R.id.id_tab_frd_img);
//		mSettingImg = (ImageButton) findViewById(R.id.id_tab_settings_img);
//
	     mLoadingView= (LoadingView) this.findViewById(R.id.loadView);
//	      
//	     ft = fm.beginTransaction();
//	     home();
//	     ft.commit();
	     
	      initWebView();
//	      initEvent();
	}
	
	@SuppressLint("JavascriptInterface")
	private void initWebView() {

		sp = getSharedPreferences("aaa", MODE_PRIVATE);

		webview.setWebChromeClient(new MyWebChromeClient(this));
		webview.getSettings().setJavaScriptEnabled(true);
		webview.getSettings().setBuiltInZoomControls(false);
		webview.getSettings().setRenderPriority(RenderPriority.HIGH);
		// 设置 缓存模式
		webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		// 开启 DOM storage API 功能
		webview.getSettings().setDomStorageEnabled(true);
		// 开启 database storage API 功能
		webview.getSettings().setDatabaseEnabled(true);
		// 设置数据库缓存路径
		String cacheDirPath = getFilesDir().getAbsolutePath()
				+ Constant.APP_CACAHE_DIRNAME;
		Log.i(Constant.TAG, "cacheDirPath=" + cacheDirPath);
		// 设置 Application Caches 缓存目录
		webview.getSettings().setDatabasePath(cacheDirPath);
		webview.getSettings().setAppCachePath(cacheDirPath);
		// 开启 Application Caches 功能
		webview.getSettings().setAppCacheEnabled(true);

		webview.addJavascriptInterface(new JavaScriptInterface(), "demo");

		// Display mDisplay = getWindowManager().getDefaultDisplay();
		// int width = mDisplay.getWidth();
		// int scalePercent = width*75/1024;
		// 三星table 187比率正常
		webview.setInitialScale(100);
		webview.getSettings().setUseWideViewPort(true);
		webview.getSettings().setLoadWithOverviewMode(true);
//		webview.loadUrl(Constant.OUTURL);
		webview.setWebViewClient(new WebViewClient(){

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url); // 在当前的webview中跳转到新的url
				//获取cookies
				CookieManager cm = CookieManager.getInstance();
				String cookies = cm.getCookie(url);
				sp.edit().putString("cook", cookies).apply();
				return true;
			}

			@Override 
            public void onPageFinished(WebView view,String url) 
            { 
//                dialog.dismiss(); 
				mLoadingView.setVisibility(View.GONE);
				webview.setVisibility(View.VISIBLE);
            } 
		});
		
		Intent i = getIntent();
		String reurl ="";
		if(i.getStringExtra("linkPhone") != null){
			reurl = Constant.OUTURL+ "/BizHall/assist/vector?assist=homepage&linkPhone="+i.getStringExtra("linkPhone")+"&"+(new Date()).getTime();;
		}else{
			String staffCode = i.getStringExtra("staffCode");
			String password= i.getStringExtra("password");
			
			
			 reurl = Constant.OUTURL+ "/BizHall/assist/vector?assist=homepage&staffCode="+staffCode+"&password="+password+"&"+(new Date()).getTime();
		}
		
		X.d("webview", reurl);
		synCookies(this,reurl);
		webview.loadUrl(reurl);
//		webview.loadUrl("http://baidu.com");


	}
	
	   public void onBackPressed() { 
	    	X.d(mContext,"返回按键");
	    	webview.loadUrl("javascript:window.doBackbutton()");
	    }
	/**
	 * 同步一下cookie
	 */

	public void synCookies(Context context, String url) {
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);
//        cookieManager.removeSessionCookie();//移除
		cookieManager.setCookie(url, cookies);
		CookieSyncManager.getInstance().sync();
	}
	
	private void initEvent() {
		mTabWeiXin.setOnClickListener(this);
		mTabAddress.setOnClickListener(this);
		mTabFrd.setOnClickListener(this);
		mTabSetting.setOnClickListener(this);
//		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
//            /**
//            *ViewPage左右滑动时
//            */
//			@Override
//			public void onPageSelected(int arg0) {
//				ft = fm.beginTransaction();
//				switch (arg0) {
//				case 0:
//					 resetImg();
//					mWeiXinImg.setImageResource(R.drawable.tab_weixin_pressed);
//					home();
//					break;
//				case 1:
//					 resetImg();
//					mAddressImg.setImageResource(R.drawable.tab_address_pressed);
//					friend();
//					break;
//				case 2:
//					 resetImg();
//					mFrdImg.setImageResource(R.drawable.tab_find_frd_pressed);
//					message();
//					break;
//				case 3:
//					 resetImg();
//					mSettingImg.setImageResource(R.drawable.tab_settings_pressed);
//					more();
//					break;
//				default:
//					break;
//				}
//				ft.commit();//生效
//			}
//
//			@Override
//			public void onPageScrolled(int arg0, float arg1, int arg2) {
//
//			}
//
//			@Override
//			public void onPageScrollStateChanged(int arg0) {
//
//			}
//		});
	}
	
	/** 
	 * 监控打开的Activity页面关闭后回传的参数 
	 */  
	public void onActivityResult(int requestCode, int resultCode, Intent data) {  
		 
			 switch (requestCode) {
			case com.asiainfo.ncrm.common.Constant.NFC_LOAD:
				if (resultCode == RESULT_OK) { 
					if(data != null){
						Bundle bundle = data.getExtras();
						String idcard = bundle.getString("result");
	//					IdCard_Bean  bean =(IdCard_Bean)data.getSerializableExtra("IdCard_Bean");
	//					net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(bean);
						String funcs = func.replace("#value", "'"+idcard+"'");
	//					Toast.makeText(mContext, json.toString(), Toast.LENGTH_LONG).show();
						webview.loadUrl("javascript:"+funcs);
					}
				}else{
					Toast.makeText(mContext, "读取证件失败，请重试", Toast.LENGTH_LONG).show();
				}
				break;
			case com.asiainfo.ncrm.common.Constant.GET_PHOTO:
				if (resultCode == RESULT_OK) { 
					Toast.makeText(mContext, "拍照上传成功", Toast.LENGTH_LONG).show();
				}else  if(resultCode == 2)
				{

				}
				else{
					Toast.makeText(mContext, "拍照上传失败", Toast.LENGTH_LONG).show();
				}
				break;
			default:
				break;
			 }
	}
	
	
	final class JavaScriptInterface {
		JavaScriptInterface() {
		}
		
		@JavascriptInterface
		public void clickOnAndroidIdCard( final String funname,  final String param) {
			X.d("show", "获得参数"+funname+"获得值:"+param);
			mHandler.post(new Runnable() {
				public void run() {
					readCard(funname, param);
				}
			});
		}
		
		@JavascriptInterface
		public void getPhotoByNbr( final String funname,  final String param) {
			X.d("show", "获得参数"+funname+"获得值:"+param);
			mHandler.post(new Runnable() {
				public void run() {
					getPhoto(funname, param);
				}
			});
		}
		
		@JavascriptInterface
		public void goBackLogin(){
			mHandler.post(new Runnable() {
				public void run() {
					back();
				}
			});
		}
		
		@JavascriptInterface
		public String getPhoneMessage(){
			return Build.MODEL;
		}
	}
	
	//获取手机信息
	public void getSys(){
		Toast.makeText(mContext, Build.MODEL, Toast.LENGTH_LONG).show();
	}
	
	public void back(){
		AlertDialog.Builder builder = new Builder(mContext);
		  builder.setMessage("是否退出到登录界面？");

		  builder.setTitle("退出");

		  builder.setPositiveButton("确认", new OnClickListener() {

		   @Override
		   public void onClick(DialogInterface dialog, int which) {
		    dialog.dismiss();
		    onBack();
//		    Main.this.finish();
		   }
		  });

		  builder.setNegativeButton("取消", new OnClickListener() {

		   @Override
		   public void onClick(DialogInterface dialog, int which) {
		    dialog.dismiss();
		   }
		  });

		  builder.create().show();
		
		
	}
	
	public void onBack(){
		super.onBackPressed();
	}
	
	public void getPhoto(String funname, String param){
		X.d(mContext, "进入图片获取.....");
		func = funname;
		paramString=param;
		Intent serverIntent = new Intent(mContext,
				getPhotoActivity.class);
		serverIntent.putExtra("param", param);
		startActivityForResult(serverIntent, com.asiainfo.ncrm.common.Constant.GET_PHOTO);
//		try {
//			JSONObject json = new JSONObject(param);
//		
//			NopaperHelper nop=new NopaperHelper();
//			BusinessModel bm=new BusinessModel("拍照", json.getString("olNbr"), json.getString("username"), json.getString("olNbr"), "crm", json.getString("staffId"));
//			nop.startNopaper(this, bm);
//		} catch (JSONException e) {
//			// TODO 自动生成的 catch 块
//			e.printStackTrace();
//		}
	}
	
	/**
	 * 读取图片
	 */

	/**
	 * 读卡
	 */
	public void readCard( String funname, String param){
//		switch (paramInt) {
//		case 1:
//			
//			break;
//
//		default:
//			break;
//		}
		
//		webview.loadUrl("javascript:"+funname+"('"+param+"')");
		
		func = funname;
		paramString= param;
		
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("请选择读卡方式！");
		//定义列表中的选项
		final String[] items = new String[]{
//
				"省内NFC(PDA读卡)",
		        "集团NFC读卡(仅wifi环境)",
		        "蓝牙读卡"
		};
		//设置列表选项
		builder.setItems(items, new OnClickListener() {
		        //点击任何一个列表选项都会触发这个方法
		        //arg1：点击的是哪一个选项
		        @Override
		        public void onClick(DialogInterface dialog, int which) {
		        	switch (which) {
						case 0:
//						blueTeeth(myaction, myarg1, mycallbackContext);
							Intent intent = new Intent(mContext,
									XTNFCActivity.class);
							startActivityForResult(intent, com.asiainfo.ncrm.common.Constant.NFC_LOAD);
							break;
					case 1:
						//调用NFC
						X.d(mContext, "进入nfc.....");
						
						Intent serverIntent = new Intent(mContext,
								NFCActivity.class);
						serverIntent.putExtra("param", paramString);
						startActivityForResult(serverIntent, com.asiainfo.ncrm.common.Constant.NFC_LOAD);
						
						break;
					case 2:
//						blueTeeth(myaction, myarg1, mycallbackContext);
						Intent i = new Intent(mContext,
								ListActivity.class);
						startActivityForResult(i, com.asiainfo.ncrm.common.Constant.NFC_LOAD);
						break;
					default:
						break;
					}
		        }
		});
		// 取消选择
		builder.setNegativeButton("取消", new OnClickListener() {
		        @Override
		        public void onClick(DialogInterface dialog, int which) {
		        }
		});
		builder.show();
		
		
	}
	
	
	
	/**
	 * 把所有图片变暗
	 */
	private void resetImg() {
		mWeiXinImg.setImageResource(R.drawable.tab_weixin_normal);
		mAddressImg.setImageResource(R.drawable.tab_address_normal);
		mFrdImg.setImageResource(R.drawable.tab_find_frd_normal);
		mSettingImg.setImageResource(R.drawable.tab_settings_normal);
	}

	@Override
	public void onClick(View arg0) {
		ft = fm.beginTransaction();
		// TODO 自动生成的方法存根
		setSelected();
		switch (arg0.getId()) {
		case R.id.id_tab_weixin:
			resetImg();
			mWeiXinImg.setImageResource(R.drawable.tab_weixin_pressed);
			home();
			break;
		case R.id.id_tab_address:
			resetImg();
			mAddressImg.setImageResource(R.drawable.tab_address_pressed);
			friend();
			break;
		case R.id.id_tab_frd:
			resetImg();
			mFrdImg.setImageResource(R.drawable.tab_find_frd_pressed);
			message();
			break;
		case R.id.id_tab_settings:
			resetImg();
			mSettingImg.setImageResource(R.drawable.tab_settings_pressed);
			more();
			break;
		default:
			break;
		}
		ft.commit();
	}
	
	private void setSelected(){
		if(fragmentPage1 != null){
			//隐藏Fragment
			ft.hide(fragmentPage1);
		}
		if(fragmentPage2 != null){
			ft.hide(fragmentPage2);
		}
		if(fragmentPage3 != null){
			ft.hide(fragmentPage3);
		}
		if(fragmentPage4 != null){
			ft.hide(fragmentPage4);
		}
	}
	
	
	private void home(){
		if(fragmentPage1 == null){
			fragmentPage1 = new fragmentPageBase("http://baidu.com",R.layout.fragment_1);
			 
//			ft.add(R.id.fl_content, fragmentPage1);
			 
		}else{
			//显示Fragment
			ft.show(fragmentPage1);
			
		}
		
		
		
		
		
		
	}
	private void friend(){
		if(fragmentPage2 == null){
			fragmentPage2 =  new fragmentPageBase("http://192.168.2.171/BizHall/sale/index",R.layout.fragment_1);
//			ft.add(R.id.fl_content, fragmentPage2);
		}else{
			ft.show(fragmentPage2);
		}
		
	}
	private void message(){
		if(fragmentPage3 == null){
			fragmentPage3 = new fragmentPageBase("http://jd.com",R.layout.fragment_1);
//			ft.add(R.id.fl_content, fragmentPage3);
		}else{
			ft.show(fragmentPage3);
		}
		
	}
	private void more(){
		if(fragmentPage4 == null){
			fragmentPage4 =  new fragmentPageBase("http://taobao.com",R.layout.fragment_1);
//			ft.add(R.id.fl_content, fragmentPage4);
		}else{
			ft.show(fragmentPage4);
		}
		
	}
}
